<?php

namespace CommonBundle\Controller;

use CommonBundle\Entity\Balance;
use CommonBundle\Entity\User;
use CommonBundle\Entity\UserProfile;
use CommonBundle\Service\BalanceService;
use CommonBundle\Service\UserProfileService;
use CommonBundle\Service\UserService;
use CommonBundle\Service\VerifyCodeService;
use Swagger\Annotations as SWG;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class RegistrationController extends RestController
{
    /**
     * Sample:
     *   {"username": "13000000000", "password": "123456", "verifyCode": "9394"}
     *
     * @Route("/mobile-register", name="mobile-register", methods={"POST"})
     * @SWG\Response(
     *     response=200,
     *     description="Mobile registration",
     * )
     * @SWG\Tag(name="auth")
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \Doctrine\Common\Annotations\AnnotationException
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     * @throws \Psr\Cache\InvalidArgumentException
     */
    public function mobileRegistrationAction(Request $request)
    {
        $service = $this->get(UserService::class);
        $userProfileServ = $this->get(UserProfileService::class);
        $balanceService = $this->get(BalanceService::class);

        // get content
        $content = json_decode($request->getContent(), true);

        // register a new user.
        /** @var User $entity */
        $entity = $service->new();

        // get username and password
        $username = $content['username'];
        $password = $content['password'];
        $phone = $content['username'];
        if(empty($username) || empty($password) || empty($phone))
            throw new \InvalidArgumentException('Username or password cannot be null.');

        // start verification code
        // phone check
        if(!preg_match("/^1\d{10}$/", $phone)) {
            return $this->Warning('非法手机号码，请填写正确的手机号码');
        }

        // check verification code
        $verifyCode = $content['verifyCode'];

        // generate verification code
        $verifyCodeService = $this->get(VerifyCodeService::class);
        $code = $verifyCodeService->getCode($phone);

        if(empty($verifyCode) || $verifyCode != $code) {
            return $this->Warning('验证码错误，请填写正确的验证码');
        }
        // end of verification code


        # encode password
        $factory = $this->get('security.encoder_factory');
        $encoder = $factory->getEncoder($entity);
        $password = $encoder->encodePassword($password, $entity->getSalt());

        $data = [
            'username' => $username,
            'password' => $password,
            'email' => $username.'@dummy.io',
            'phone' => $phone,
            'enabled' => true,
        ];
        if(array_key_exists('recommendedUser', $content)) {
            $data['recommendedUser'] = $content['recommendedUser'];
        }

        // add user
        $user = $service->update($entity, $data);

        if ($user) {
            // add profile
            /** @var UserProfile $profile */
            $profile = $userProfileServ->new();
            $profile->setUser($user);
            $userProfileServ->update($profile);

            /** @var Balance $balance */
            $balance = $balanceService->new();
            $balance->setUser($user);
            $balanceService->update($balance);
        }

        return $this->Success($entity);
    }

}
